package com.example.idlefish.HomeAndSearch

import android.app.Activity
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.example.idlefish.GoodsInfo.pojo.Class_t
import com.example.idlefish.PublicModule.NetworkSettings
import com.example.idlefish.R
import org.json.JSONArray
import java.io.BufferedReader
import java.io.InputStreamReader
import java.net.HttpURLConnection
import java.net.URL

class TypeSheetAdapter  (
    private val items: List<Class_t>, // 数据源
    private val onItemClick: (Int) -> Unit, // 点击事件回调
    private val recyclerView: RecyclerView,
    private val listener: OnSubItemClickListener // 回调到 Activity
) : RecyclerView.Adapter<TypeSheetAdapter.TypeSheetViewHolder>() {
    class TypeSheetViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
        val typename : TextView = itemView.findViewById(R.id.typename)
        val typee: RecyclerView = itemView.findViewById(R.id.re_rype)
    }
    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int):TypeSheetViewHolder {
        val view = LayoutInflater.from(parent.context).inflate(R.layout.type_sheet, parent, false)
        val viewHolder = TypeSheetViewHolder(view)
        return viewHolder
    }

    override fun onBindViewHolder(holder: TypeSheetViewHolder, position: Int) {
        val item = items[position]
        holder.typename.text = item.name

        // 初始化子级 RecyclerView
        holder.typee.layoutManager = LinearLayoutManager(holder.itemView.context, LinearLayoutManager.HORIZONTAL, false)
        //根据标签得到list

        //
        // var list1  = mutableListOf<one_goods_data>()
        // getOnetypedata(list1, position)
        // println(list1 + "list1")
        // val subAdapter = TypeAdapter(list1, { selectedItem ->
        //     println("Clicked item: $selectedItem")
        // }, holder.typee) // 子级 Adapter
        // holder.typee.adapter = subAdapter
        //
        // holder.itemView.setOnClickListener { onItemClick(position) }
        val list1 = mutableListOf<one_goods_data>()
        val subAdapter = TypeAdapter(list1,{childPosition, data ->
        // 回调内层点击事件到 Activity
        listener.onSubItemClick(position, childPosition, data)
        })
        holder.typee.adapter = subAdapter

        getOnetypedata(holder, list1, item.id) { updatedList ->
            subAdapter.notifyDataSetChanged() // 通知 Adapter 数据更新
        }

        holder.itemView.setOnClickListener { onItemClick(position) }

    }

    override fun getItemCount(): Int = items.size

    fun getOnetypedata(holder: TypeSheetViewHolder, list1: MutableList<one_goods_data>, temp: Int, callback: (List<one_goods_data>) -> Unit) {
        Thread {
            try {
                val urlString = "${NetworkSettings.HTTP}/product/getOnetype?kind=${temp}"
                val url = URL(urlString)
                val conn = url.openConnection() as HttpURLConnection
                conn.requestMethod = "GET"

                val reader = BufferedReader(InputStreamReader(conn.inputStream), 8192)
                val response = StringBuilder()
                var line: String?
                while (reader.readLine().also { line = it } != null) {
                    response.append(line)
                }
                reader.close()

                val tempList = mutableListOf<one_goods_data>() // 临时列表
                val jsonArray = JSONArray(response.toString())
                for (i in 0 until jsonArray.length()) {
                    val obj = jsonArray.getJSONObject(i)
                    val id = obj.getInt("id")
                    val name = obj.getString("name")
                    tempList.add(one_goods_data(id, name))
                }

                // 在主线程更新数据
                (holder.itemView.context as? Activity)?.runOnUiThread {
                    list1.clear()
                    list1.addAll(tempList)
                    callback(list1) // 调用回调通知数据已更新
                }

            } catch (e: Exception) {
                Log.e("Product", "Exception occurred: ${e.message}", e)
            }
        }.start()
    }

}
